package com.ruoyi.web.controller.system;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.tree.TreeHelper;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.ElectricFence;
import com.ruoyi.system.domain.request.dept.CompanyExistNameParam;
import com.ruoyi.system.domain.tree.DeptTree;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
@Slf4j
public class SysDeptController extends BaseController {
    private static final String PREFIX = "/system/dept";

    @Autowired
    private ISysDeptService deptService;

    @ApiOperation("组织架构列表")
    @ApiOperationSupport(includeParameters = {"deptName","status"})
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    @ApiOperation("组织架构树导出")
    @ApiOperationSupport(includeParameters = {"deptName","status"})
    @Log(title = "组织架构", businessType = BusinessType.EXPORT)
    @PostMapping("/listExport")
    public void list(SysDept dept, HttpServletResponse response) {
        List<SysDept> deptList = deptService.selectDeptListWithVehicleCount(dept);
        if (ObjectUtils.isNotEmpty(deptList)) {
            //转成树结构方便递归计算车辆总树,计算后还原成普通列表
            List<DeptTree> treeList = TreeHelper.buildTree(deptList.stream().map(DeptTree::new).collect(Collectors.toList()));
            treeList.stream().forEach(DeptTree::sumVehicleCount);
            deptList = TreeHelper.treeToList(treeList).stream().map(DeptTree::toSysDept).collect(Collectors.toList());
        }
        new ExcelUtil<>(SysDept.class).exportExcel(response, deptList, "公司管理");
    }


    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().equals(deptId) || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId.toString()));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    @ApiOperation("新增组织")
    @ApiOperationSupport(includeParameters = {"parentId", "deptName", "shortName", "leader", "phone", "picture", "address", "remark"})
    @Log(title = "组织架构", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        checkExistName(new CompanyExistNameParam(dept.getParentId(), dept.getDeptName(), null));
        return toAjax(deptService.insertDept(dept));
    }

    @ApiOperation("编辑组织")
    @ApiOperationSupport(includeParameters = {"deptId", "parentId", "deptName", "shortName", "leader", "phone", "picture", "address", "remark"})
    @Log(title = "组织架构", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        checkExistName(new CompanyExistNameParam(dept.getParentId(), dept.getDeptName(), deptId));
        if (dept.getParentId().equals(deptId)) {
            return error("修改节点'" + dept.getDeptName() + "'失败，上级节点不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该节点包含未停用的子节点！");
        }
        return toAjax(deptService.updateDept(dept));
    }

    @ApiOperation("删除组织")
    @Log(title = "组织架构", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return warn("存在下级节点,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return warn("节点存在用户,不允许删除");
        }
        deptService.checkDeptExistDevice(deptId);
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    @ApiOperation("文件上传")
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestPart MultipartFile[] file){
        return success(uploadFile(file, "company"));
    }

    @ApiOperation("校验名称是否存在")
    @PostMapping("/checkExistName")
    public AjaxResult checkExistName(@Validated @RequestBody CompanyExistNameParam param) {
        deptService.checkExistName(param);
        return success();
    }

    @ApiOperation("实时视频树列表")
    @GetMapping("/videoTree")
    public AjaxResult videoTree(@RequestParam(required = false) boolean onlyOnline){
        return success(deptService.videoTree(onlyOnline));
    }

    @ApiOperation("组织架构树列表")
    @GetMapping("/treeList")
    public AjaxResult treeList(){
        List<SysDept> deptList = deptService.selectDeptListWithVehicleCount(new SysDept());
        List<DeptTree> deptTreeList = deptList.stream().map(DeptTree::new).collect(Collectors.toList());
        return success(TreeHelper.buildTree(deptTreeList));
    }

    @ApiOperation("指令下发设备树列表")
    @GetMapping("/orderSendDeviceTree")
    public AjaxResult orderSendDeviceTree(){
        return success(deptService.orderSendDeviceTree());
    }


    @ApiOperation("组织架构用户树列表")
    @PostMapping("/userTree")
    public AjaxResult userTree() {
        return success(deptService.userTree());
    }

    @ApiOperation("围栏树列表")
    @ApiOperationSupport(includeParameters = {"type"})
    @PostMapping("/polygonTree")
    public AjaxResult polygonTree(ElectricFence param) {
        return success(deptService.polygonTree(param));
    }

    @ApiOperation("带父节点的组织架构树列表")
    @GetMapping("/treeListWithParents")
    public AjaxResult treeListWithParents(){
        return success(deptService.treeListWithParents());
    }
}
